<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Requests\AddressRequest;
use App\Http\Controllers\Controller;
use DB,Session;

class AddressController extends CommonController
{
    // 显示收货地址列表
    public function index()
    {
        $userid = Session::get("userData")->id;
        $address =  DB::table("user_address")->where("user_id", $userid)->get();
        return view("home.user.address", compact("address"));
    }
    
    // 添加收货地址
    public function addressTodo(AddressRequest $request)
    {
        $userid = Session::get("userData")->id;
        // 获取数据
        $address = $request->except("_token");
        $address['user_id'] = $userid;
        // 最大添加二十个收货地址
        $count = DB::table('user_address')->where('user_id', $userid)->count();
        if($count >= 20){
            return back()->with(["info" => "最大添加二十个地址"]);
        }
        
        // 执行数据创建
        $yang = DB::table("user_address")->insert($address);
        if (FALSE !== $yang ) {
            // 如果只有一个收货地址则为默认地址
            $addr = DB::table('user_address')->where('user_id', $userid)->get();
            if(count($addr) == 1){
                DB::table('user_address')->where('id', $addr[0]->id)->update(['addr_status'=>1]);
            }
            return back();
        }else {
            return back()->with(["info" => "添加地址失败"]);
        }
    }
    
    // 修改默认地址？？？
    public function getAddress(Request $request){
        $upid = $request->get('upid');
        return response()->json(['status'=>1]);
    }
    
    // 删除收货地址
    public function destroy($id)
    {
        $userid = Session::get('userData')->id;
        $res = DB::table("user_address")->where("id", $id)
                ->where('user_id', $userid)
                ->delete();
        if(false !== $res){
            // 修改剩下的某一个为默认地址
            $address = DB::table('user_address')->where('user_id', $userid)->first();
            if($address){
                DB::table('user_address')->where('id', $address->id)->update(['addr_status'=>1]);
            }
            return back();
        } else {
            return back()->with(['info'=>'删除失败']);
        }
    }
    
    // 修改地址
    public function editAddress(AddressRequest $request, $id)
    {
        // 获取数据
        $data = ($request->except("_token"));
        // 修改数据库
        if (!$request->addr_county)
        {
            $data['addr_county'] = "";
        }
        DB::table("user_address")->where("id", $id)->update($data);
        return back();
    }
    
    /**
     * 默认地址
     * @param  1为默认地址
     */
    public function status($id)
    {
        $userid = Session::get("userData")->id;
        DB::table("user_address")->where("user_id", $userid)->update(["addr_status" => "0"]);
        DB::table("user_address")->where("user_id", $userid)->where("id", $id)->update(["addr_status" => "1"]);
        return redirect("/address");
    }
}
